package com.lalosoft.misgastos.dao;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.Log;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.lalosoft.misgastos.config.DatabaseHelper;
import com.lalosoft.misgastos.domain.Account;

public class AccountDao implements AbstractDao<Account> {
	
	private static String TAG = "AccountDao";
	
	private DatabaseHelper helper;
	
	public AccountDao(Context context){
		OpenHelperManager.setOpenHelperClass(DatabaseHelper.class);
		helper = (DatabaseHelper)OpenHelperManager.getHelper(context);
	}

	@Override
	public void delete(Account object) {
		try {
			helper.getAccountDao().delete(object);
		} catch (SQLException e) {
			Log.e(TAG, "ERROR ACCOUNTDAO: " + e.getMessage(), e);
		}
	}

	@Override
	public List<Account> findAll() {
		List<Account> list = null;
		try {
			list = helper.getAccountDao().queryForAll();
		} catch (SQLException e) {
			Log.e(TAG, "ERROR ACCOUNTDAO: " + e.getMessage(), e);
		}
		return list;
	}

	@Override
	public Account findByID(int id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void insert(Account object) {
		try {
			helper.getAccountDao().create(object);
		} catch (SQLException e) {
			Log.e(TAG, "ERROR ACCOUNTDAO: " + e.getMessage(), e);
		}
	}

	@Override
	public void update(Account object) {
		try {
			helper.getAccountDao().update(object);
		} catch (SQLException e) {
			Log.e(TAG, "ERROR ACCOUNTDAO: " + e.getMessage(), e);
		}
	}
	
	public Account findByUserAndPass(String username, String password) throws SQLException{
		List<Account> list = null;
		Map<String, Object> fieldValues = new HashMap<String, Object>();
		fieldValues.put("username", username);
		fieldValues.put("password", password);
		list = helper.getAccountDao().queryForFieldValues(fieldValues);
		if(list.size() > 0){
			return list.get(0);
		} else {
			return null;
		}
	}

}
